<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    body{
      margin: 0;
      padding: 15px;
    }
    .data-panel{
      border: 1px solid rgba(0,0,0,.2);
      border-radius: 8px;
      padding: 15px 20px;
      margin-top: 15px;
      position: relative;
    }
    .data-panel-title {
      position: absolute;
      top: -15px;
      left: 20px;
      background-color: rgba(255,255,255,1);
      font-size: 1em;
      font-weight: initial;
    }
    /* 新增: 定义一个类来去掉列表项前边的黑点 */
    .no-bullet {
      list-style-type: none;
      padding: 0;
      margin: 0;
    }
    /* 新增: 进度条样式 */
    .progress-bar {
      width: 100%;
      margin-top: 5px;
      display: flex;
      align-items: center;
      justify-content: space-between; /* 新增: 使内容两端对齐 */
    }
    .progress-bar-panel{
      background-color: #f3f3f3;
      border-radius: 5px;
      overflow: hidden;
      flex: 1;
    }
    .progress-bar-fill {
      height: 20px;
      background-color: #4caf50; /* 默认绿色 */
      width: 50%;
      transition: width 0.3s ease;
    }
    .progress-bar-fill.error {
      background-color: #f44336; /* 错误状态为红色 */
      cursor: pointer; /* 添加鼠标手型 */
    }
    .progress-bar-fill.running {
      background-color: #2196F3; /* 运行中状态为蓝色 */
    }
    /* 新增: 定义按钮组和刷新秒数输入框的布局样式 */
    .button-group {
      display: flex;
      gap: 10px;
    }
    .refresh-rate-container {
      display: flex;
      align-items: center;
    }
    .control-container {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
    /* 新增: 输入框样式 */
    input[type="text"], input[type="number"] {
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
      font-size: 14px;
      transition: border-color 0.3s ease;
    }
    input[type="text"]:focus, input[type="number"]:focus {
      border-color: #4caf50;
      outline: none;
      box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
    }
    /* 新增: 输入框标签样式 */
    label {
      font-size: 14px;
      color: #333;
      margin-top: 10px;
      margin-bottom: 10px;
    }
    /* 新增: 定义横向排列样式 */
    .horizontal-inputs {
      display: flex;
      gap: 10px; /* 设置输入框之间的间距 */
      align-items: center; /* 垂直居中对齐 */
    }
    /* 新增: 按钮样式 */
    button {
      padding: 8px 16px; /* 增加按钮的内边距 */
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px; /* 增加按钮的字体大小 */
      transition: background-color 0.3s ease;
    }
    button:hover {
      background-color: #45a049;
    }
    button:active {
      background-color: #3e8e41;
    }
    /* 新增: 按钮组样式 */
    .job-buttons {
      display: flex;
      gap: 5px;
      margin-left: 10px; /* 删除: margin-left: 10px; */
    }
    /* 修改: 进度条右边按钮的样式 */
    .job-buttons button {
      padding: 5px 10px; /* 减少按钮的内边距 */
      font-size: 12px; /* 减少按钮的字体大小 */
    }
    /* 修改: 模态对话框样式 */
    .modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 1000;
      opacity: 0;
      visibility: hidden;
      transition: opacity 0.3s, visibility 0.3s;
    }
    .modal.active {
      opacity: 1;
      visibility: visible;
      display: block;
    }
    .modal-content {
      position: relative;
      background: #fff;
      width: 90%;
      max-width: 500px;
      margin: 20vh auto;
      padding: 20px;
      border-radius: 8px;
      transform: translateY(-20px);
      transition: transform 0.3s;
    }
    .modal.active .modal-content {
      transform: translateY(0);
    }
    .modal-close {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 30px;
      height: 30px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: #666;
      background: none;
      border: none;
      padding: 0;
    }
    .modal-close:hover {
      color: #000;
    }
    .modal-body {
      margin-top: 10px;
      color: #333;
      line-height: 1.5;
    }
    /* 新增: 提示框样式 */
    .alert-box {
      background-color: #f44336;
      color: white;
      padding: 15px;
      margin-bottom: 15px;
      border-radius: 5px;
      position: relative;
      display: block;
    }
    .alert-box.show {
      display: block;
    }
    .alert-close {
      position: absolute;
      top: 5px;
      right: 10px;
      cursor: pointer;
      font-size: 20px;
      color: white;
    }
    .alert-close:hover {
      color: #ddd;
    }
  </style>
</head>
<body>
  <!-- 新增: 提示框 -->
  <div class="alert-box" id="alert-box">
    <span id="alert-message">这是一个提示框</span>
    <span class="alert-close" onclick="closeAlert()">&times;</span>
  </div>

  <div class="data-panel">
    <span class="data-panel-title">Source</span>
    <div class="horizontal-inputs">
      <input type="text" id="source-host" placeholder="Host" />
      <input type="text" id="source-port" placeholder="Port" value="80" />
      <input type="text" id="source-username" placeholder="Username" value="admin" />
      <input type="text" id="source-password" placeholder="Password" value="Harbor12345" />
    </div>
  </div>
  <div class="data-panel">
    <span class="data-panel-title">Target</span>
    <div class="horizontal-inputs">
      <input type="text" id="target-host" placeholder="Host" />
      <input type="text" id="target-port" placeholder="Port" value="80" />
      <input type="text" id="target-username" placeholder="Username" value="admin" />
      <input type="text" id="target-password" placeholder="Password" value="Harbor12345" />
    </div>
  </div>

  <!-- Job Name 面板移动到这里 -->
  <div class="data-panel">
    <span class="data-panel-title">Job Name</span>
    <div class="horizontal-inputs">
      <input type="text" id="job-name" placeholder="Job Name" />
      <input type="text" id="project-name" placeholder="Project Name" /> <!-- 新增: 将project-name输入框添加到Job Name面板中 -->
    </div>
  </div>

  <div class="data-panel">
    <span class="data-panel-title">List</span>
    <div class="control-container">
      <div class="button-group">
        <button onclick="addJob()">添加任务</button>
      </div>
      <div class="refresh-rate-container">
        <input type="number" id="refresh-rate" placeholder="刷新秒数" min="1" value="15" onchange="setRefreshInterval()" />
      </div>
    </div>
    <ul class="no-bullet" id="job-list">
    </ul>
  </div>

  <!-- 新增: 模态对话框 -->
  <div class="modal" id="modal">
    <div class="modal-content">
      <button class="modal-close" onclick="closeModal()">&times;</button>
      <div class="modal-body" id="modal-body"></div>
    </div>
  </div>

  <script>
    // 新增: 显示模态对话框
    function showModal(message) {
      const modal = document.getElementById('modal');
      const modalBody = document.getElementById('modal-body');
      modalBody.innerHTML = message;
      modal.classList.add('active');
    }

    // 新增: 关闭模态对话框
    function closeModal() {
      const modal = document.getElementById('modal');
      modal.classList.remove('active');
    }

    // 新增: 关闭模态对话框的事件监听
    document.addEventListener('DOMContentLoaded', function() {
      const modal = document.getElementById('modal');
      const closeBtn = document.querySelector('.modal-close');
      closeBtn.onclick = closeModal;
      window.onclick = function(event) {
        if (event.target == modal) {
          closeModal();
        }
      }
    });

    // 新增: 转义HTML字符的函数
    function escapeHtml(str) {
      if (!str) return '未知错误';
      return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;')
        .replace(/\n/g, '<br>')
        .replace(/\r/g, '');
    }

    // 修改列表项添加函数，使用转义函数处理错误信息
    function addJobItems(jobs) {
      const jobList = document.getElementById('job-list');
      jobList.innerHTML = ''; // 清空现有列表
      jobs.forEach(job => {
        const li = document.createElement('li');
        li.setAttribute('data-id', job.id);
        
        // 根据状态设置进度条颜色类名
        let statusClass = '';
        let errorClickHandler = '';
        if (job.status === 99) { // 错误状态
          statusClass = 'error';
          // 添加点击事件，使用转义后的错误信息
          const escapedError = escapeHtml(job.error_message);
          errorClickHandler = `onclick="showErrorMessage('${escapedError}')"`;
        } else if (job.status === 1) { // 运行中
          statusClass = 'running';
        }

        li.innerHTML = `
          ${escapeHtml(job.name)}
          <div class="progress-bar">
            <div class="progress-bar-panel">
                <div class="progress-bar-fill ${statusClass}" ${errorClickHandler} style="width: ${job.progress}%;"></div>
            </div>
            <div class="job-buttons">
              <button onclick="deleteJob(${job.id})">删除任务</button>
            </div>
          </div>
        `;
        jobList.appendChild(li);
      });
    }

    // 删除任务
    function deleteJob(jobId) {
      if (!confirm('确定要删除这个任务吗？')) {
        return;
      }
      
      fetch(`/api/delete_job/${jobId}`, {
        method: 'DELETE'
      })
      .then(response => {
        if (!response.ok) {
          return response.json().then(data => Promise.reject(data.error));
        }
        return response.json();
      })
      .then(data => {
        showModal(data.message);
        updateProgress(); // 刷新任务列表
      })
      .catch(error => {
        showModal('删除任务失败: ' + error);
      });
    }

    // 修改: 定义一个函数来更新进度条
    function updateProgress() {
      fetch('/api/job_list')
        .then(response => response.json())
        .then(data => {
          addJobItems(data);
        })
        .catch(error => console.error('Error fetching job list:', error));
    }

    // 修改: 定期调用updateProgress函数，使用输入框中的值
    let refreshIntervalId;
    function setRefreshInterval() {
      const refreshRate = document.getElementById('refresh-rate').value;
      clearInterval(refreshIntervalId);
      refreshIntervalId = setInterval(updateProgress, refreshRate * 1000);
    }

    // 新增: 从 localStorage 读取数据并填充到输入框中
    function loadInputsFromLocalStorage() {
      const inputs = [
        'source-host', 'source-port', 'source-username', 'source-password',
        'target-host', 'target-port', 'target-username', 'target-password',
        'job-name', 'refresh-rate'
      ];
      inputs.forEach(inputId => {
        const value = localStorage.getItem(inputId);
        if (value) {
          document.getElementById(inputId).value = value;
        }
      });
    }

    // 新增: 将输入框的值保存到 localStorage
    function saveInputToLocalStorage(event) {
      const inputId = event.target.id;
      localStorage.setItem(inputId, event.target.value);
    }

    // 修改: 页面加载完成后立即更新一次进度条并设置刷新间隔，同时加载输入框的值
    window.onload = () => {
      updateProgress();
      setRefreshInterval();
      // 新增: 显示提示框
      showAlert('欢迎使用同步镜像工具');
      // 新增: 加载输入框的值
      loadInputsFromLocalStorage();
    };

    // 示例函数，实际功能需要根据需求实现
    function addJob() {
      const jobName = document.getElementById('job-name').value.trim();
      const projectName = document.getElementById('project-name').value.trim(); // 获取项目名称
      const sourceHost = document.getElementById('source-host').value.trim();
      const sourcePort = document.getElementById('source-port').value.trim();
      const sourceUsername = document.getElementById('source-username').value.trim();
      const sourcePassword = document.getElementById('source-password').value.trim();
      const targetHost = document.getElementById('target-host').value.trim();
      const targetPort = document.getElementById('target-port').value.trim();
      const targetUsername = document.getElementById('target-username').value.trim();
      const targetPassword = document.getElementById('target-password').value.trim();

      // 非空判断（移除jobName）
      if (!sourceHost || !sourcePort || !sourceUsername || !sourcePassword || 
          !targetHost || !targetPort || !targetUsername || !targetPassword) {
        showModal('除任务名称外，其他字段都必须填写');
        return;
      }

      const newJob = {
        name: jobName,  // 可以为空
        projects: [projectName],  // 将项目名称添加到项目数组中
        source_host: sourceHost,
        source_port: sourcePort,
        source_username: sourceUsername,
        source_password: sourcePassword,
        target_host: targetHost,
        target_port: targetPort,
        target_username: targetUsername,
        target_password: targetPassword
      };
      fetch('/api/add_job', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(newJob)
      })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok ' + response.statusText);
        }
        return response.json();
      })
      .then(data => {
        console.log('New job added:', data);
        updateProgress();
        showModal('任务添加成功');
        // 新增: 保存输入框的值
        saveInputToLocalStorage({ target: { id: 'job-name', value: jobName } });
        saveInputToLocalStorage({ target: { id: 'project-name', value: projectName } });
        saveInputToLocalStorage({ target: { id: 'source-host', value: sourceHost } });
        saveInputToLocalStorage({ target: { id: 'source-port', value: sourcePort } });
        saveInputToLocalStorage({ target: { id: 'source-username', value: sourceUsername } });
        saveInputToLocalStorage({ target: { id: 'source-password', value: sourcePassword } });
        saveInputToLocalStorage({ target: { id: 'target-host', value: targetHost } });
        saveInputToLocalStorage({ target: { id: 'target-port', value: targetPort } });
        saveInputToLocalStorage({ target: { id: 'target-username', value: targetUsername } });
        saveInputToLocalStorage({ target: { id: 'target-password', value: targetPassword } });
      })
      .catch(error => {
        console.error('Error adding job:', error);
        showModal('添加任务失败，请检查输入并重试');
      });
    }

    // 修改显示错误信息的函数，支持HTML换行
    function showErrorMessage(message) {
      showModal(`<strong>错误信息：</strong><br>${message}`);
    }

    // 添加点击背景关闭模态框的功能
    document.getElementById('modal').addEventListener('click', function(event) {
      if (event.target === this) {
        closeModal();
      }
    });

    // 新增: 显示提示框
    function showAlert(message) {
      const alertBox = document.getElementById('alert-box');
      const alertMessage = document.getElementById('alert-message');
      alertMessage.innerHTML = message;
      alertBox.classList.add('show');
    }

    // 新增: 关闭提示框
    function closeAlert() {
      const alertBox = document.getElementById('alert-box');
      alertBox.classList.remove('show');
    }
  </script>
</body>
</html>















